
import subprocess
import time
import re
from datetime import datetime
from collections import defaultdict

count = 0
load = 0
cpu_rate = 0
mem_rate = 0
utilper = 0
cpu_rate_regex = "(?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mid" 
load_regex = "load average: (?P<value>[0-9.]+), "
mem_total_regex = " (?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mtotal"
mem_used_regex = " (?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mused"
utilper_regex = "sda[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)\n"

while True:
    p = subprocess.Popen("top -n 1", shell=True, stdout=subprocess.PIPE)
    out = p.stdout.readlines()
    
    # 获取负载、CPU使用率、内存使用率指标
    try:
        load += float(re.search(load_regex, out[0].decode("utf-8")).group('value')) if count > 60 else 0
        cpu_rate += float(re.search(cpu_rate_regex, out[2].decode("utf-8")).group('value'))
        mem_total = float(re.search(mem_total_regex, out[3].decode("utf-8")).group('value'))
        mem_used = float(re.search(mem_used_regex, out[3].decode("utf-8")).group('value'))
        mem_rate += round(mem_used/mem_total, 2)
    except Exception as e:
        print(out[2])
        continue
    
    # 计算均值/分布
    count += 1
    avg_load = round(load/(count-60), 2) if count > 60 else 0
    avg_cpu_rate = round(100-cpu_rate/count, 2)
    avg_mem_rate = round(mem_rate/count, 2)
    
    print("{}   -   {}  {}  {}".format(datetime.now(), avg_load, avg_cpu_rate, avg_mem_rate))


